package com.central.apps.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.service.HandlerService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2022/8/23.
 */
@Slf4j
@RestController
@Api(tags = "测试controller")
@RequestMapping("/instorage")
public class InstorageController {

    /*
    * 选择作业计划之后，将作业计划中，子表数据插入到对应的工作任务，人员，物料表中
    * */
    @Autowired
    private HandlerService handlerService;
    @GetMapping("/insertInstoline")
    @Transactional
    public String InsertInstoline(String ponum,String instonum) throws Exception {
        //String ponum = (String) insae.get("ponum");//采购订单编号
        //String instonum = (String) insae.get("instonum");//入库单号

        //查询采购订单里的 采购订单明细信息子表，把对应的物料信息查询出来，插入到入库明细子表中
        /*
        * 1.根据采购订单编号，查询子表数据 gq_poline  需要的字段：itemnum（物质编码），itemdesc（名称），unitcost（单位成本）,linecost（行成本）
        * tax1code（税代码），tax(税)，tax1(税额)，amounttoreceive（待接收的数量），receivedqty（已接收的数量），receivedunitcost（已接收单位成本）
        * receivedtotalcost（已接收行成本），receiptscomplete（接收完成），
        * 2.
        * */
//        if(instonum==null||"".equals(instonum)){
//            Map<String, Object> woMap = new HashMap<>();
//            handlerService.addBizNum("instorageApp", "gq_instorage", woMap);
//            instonum=(String)woMap.get("instonum");
//        }

        String sql = "select * from gq_poline where ponum = '"+ponum+"'";
        List<Map<String,Object>> datas = new ArrayList<>();
        List<Map<String,Object>> list = handlerService.findBySql(sql);
        if(CollectionUtils.isNotEmpty(list)){
            for(Map<String,Object> map:list){
                Map<String, Object> insertMap = new HashMap<>();
                insertMap.put("instonum",instonum);// 入库单号
                insertMap.put("ponum",ponum);// 采购订单号
                insertMap.put("polinenum", map.get("polinenum"));// 行号
                insertMap.put("linetype", map.get("linetype"));// 行类型
                insertMap.put("itemnum", map.get("itemnum"));// 物料编码
                insertMap.put("itemdesc", map.get("itemdesc"));// 物料名称
                insertMap.put("model", map.get("modelnum"));// 型号
                insertMap.put("unit", map.get("orderunit"));// 计量单位
                insertMap.put("unitcost", map.get("unitcost"));// 单位成本
                insertMap.put("tax1code", map.get("tax1code"));// 行成本
                insertMap.put("tax", map.get("tax"));// 行号
                insertMap.put("tax1", map.get("tax1"));// 行号
                insertMap.put("beforetax", map.get("beforetax"));// 行号
                insertMap.put("amounttoreceive", map.get("amounttoreceive"));// 行号
                insertMap.put("receivedlinecost", map.get("receivedlinecost"));// 行号
                insertMap.put("receivedqty", map.get("receivedqty"));// 行号
                insertMap.put("receivedunitcost", map.get("receivedunitcost"));// 行号
                insertMap.put("receivedtotalcost", map.get("receivedtotalcost"));// 行号
                insertMap.put("receiptscomplete", map.get("receiptscomplete"));// 行号
                insertMap.put("rejectedqty", map.get("rejectedqty"));// 行号
                insertMap.put("inspectreceive", map.get("inspectreceive"));// 行号
                insertMap.put("inspectqty", map.get("inspectqty"));// 行号
                insertMap.put("requestedby", map.get("requestedby"));// 行号
                insertMap.put("reqdeliverydate", map.get("reqdeliverydate"));// 行号
                insertMap.put("manufacturer", map.get("manufacturer"));// 行号
                insertMap.put("contractnum", map.get("contractnum"));// 行号
                insertMap.put("contractid", map.get("contractid"));// 行号
                insertMap.put("contractlineid", map.get("contractlineid"));// 行号insertMap.put("contractnum", map.get("contractnum"));// 行号
                insertMap.put("contractlinenum", map.get("contractlinenum"));// 行号
                insertMap.put("shipto", map.get("shipto"));// 行号
                insertMap.put("billto", map.get("billto"));// 行号
                insertMap.put("shiptoattn", map.get("shiptoattn"));// 行号
                insertMap.put("rfqnum", map.get("rfqnum"));// 行号
                insertMap.put("rfqlinenum", map.get("rfqlinenum"));// 询价单行号
                insertMap.put("psnum", map.get("psnum"));// 验收单号
                insertMap.put("projectnum", map.get("projectnum"));// 项目编号

                datas.add(insertMap);
            }
            //先批量删除在插入
            String del = "delete from gq_instoline where instonum = '"+instonum+"'";
            handlerService.updateBySql(del);
            //插入到接收入库的采购订单明细表
            handlerService.batchInsert("instorageApp","gq_instoline",datas);
        }
        JSONObject json = new JSONObject();
        json.put("code", "0");
        json.put("msg", "");




        return json.toString();
    }


    @GetMapping("/selectAblebatch")
    @Transactional
    public Map<String,Object> selectAblebatch(String id) throws Exception {
        Map<String,Object> map = new HashMap<>();
        if (StringUtils.isNotEmpty(id)){
            String sql = "select * from gq_instoline where id = '"+id+"'";
            List<Map<String,Object>> list = handlerService.findBySql(sql);
            String itemnum = (String )list.get(0).get("itemnum");
            String sql2 = "select * from gq_item where itemnum = '"+itemnum+"'";
            List<Map<String,Object>> list2 = handlerService.findBySql(sql2);
            String enablebatch =(String ) list2.get(0).get("enablebatch");

            if(enablebatch==null||"".equals(enablebatch)){
                enablebatch="0";
            }
            map.put("enablebatch",enablebatch);
        }
        return map;
    }
    @PostMapping("/generateBarcode")
    public String generateBarcode(@RequestBody Map<String,Object> params) throws Exception {

        String ids = MapUtils.getString(params,"ids");

        List<Map<String, Object>> prtdlList = handlerService.findBySql("select * from gq_instoline where id in (" + ids+") and (converttobc !=1 or converttobc is  null)");
        List<Map<String, Object>> bclList = new ArrayList<>();
        StringBuffer id = new StringBuffer();
        JSONObject json = new JSONObject();
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(prtdlList)){
            for (Map<String, Object> stringObjectMap : prtdlList) {
                Map<String, Object> bcMap = new HashMap<>();
                bcMap.put("itemnum", stringObjectMap.get("itemnum"));
                bcMap.put("itemdesc", stringObjectMap.get("itemdesc"));
                bcMap.put("model", stringObjectMap.get("model"));
                bcMap.put("manufacturer", stringObjectMap.get("manufacturer"));
                bcMap.put("batchnum", stringObjectMap.get("batchnum"));
                bcMap.put("expirydate", stringObjectMap.get("life"));
                bcMap.put("itemtype", stringObjectMap.get("linetype"));
                bcMap.put("addtype","gq_instoline");
                bcMap.put("addid",stringObjectMap.get("id"));
                Object res = handlerService.insert("gq_barcode", bcMap);
                id.append(res).append(",");
                bcMap.put("id",res);
                bclList.add(bcMap);
                // 更新标记字段
                handlerService.updateBySql("update gq_instoline set converttobc = '1' where id = " + stringObjectMap.get("id"));
            }

            json.put("code", "0");
            json.put("msg", "添加到条码管理成功, 请到条码管理界面查询数据!");
            json.put("codeIds", id.toString());
            json.put("bclList", bclList);
        }else {
            json.put("code", "1");
            json.put("msg", "条码已生成，不可重复生成");
        }

        return json.toString();
    }
}
